package com.soil.code.generation.database.mysql.repository;

import com.soil.code.generation.database.model.ColumnInfo;
import com.soil.code.generation.database.mysql.repository.po.MysqlColumnInfoPO;
import com.soil.code.generation.database.mysql.repository.mapper.MysqlColumnsViewMapper;
import com.soil.code.generation.database.repository.ColumnInfoRepository;
import com.ssy.gaea.common.collection.CollectionUtils;

import java.util.List;

/**
 * @author zeno
 */
public class MysqlColumnInfoRepository implements ColumnInfoRepository{

  private MysqlColumnsViewMapper mapper;

  public MysqlColumnInfoRepository(MysqlColumnsViewMapper mapper){
    this.mapper = mapper;
  }

  @Override
  public List<ColumnInfo> findColumnInfos( String dbName, String tableName ){

    List<MysqlColumnInfoPO> columnsInfos = mapper.findColumnsInfo(dbName,tableName);

    return CollectionUtils.convert(columnsInfos, MysqlColumnInfoRepository::createFrom);
  }

  private static ColumnInfo createFrom( MysqlColumnInfoPO po ){
    ColumnInfo columnInfo = new ColumnInfo();
    columnInfo.setName(po.getColumnName());
    columnInfo.setJavaType(MysqlColumTypeMapper.getJavaType(po.getDataType()));
    columnInfo.setIsPrimaryKey("PRI".equalsIgnoreCase(po.getColumnKey()));
    if( columnInfo.getIsPrimaryKey() ){
      columnInfo.setIsAutoIncrement("auto_increment".equals(po.getExtra()));
    }
    columnInfo.setIsNullable("YES".equalsIgnoreCase(po.getIsNullable()));
    columnInfo.setCharLength(po.getCharacterMaximumLength());
    columnInfo.setComment(po.getColumnComment());
    return columnInfo;
  }
}
